const NodeMediaServer = require('node-media-server');

const config = {
    rtmp: {
        port: 1935,
        chunk_size: 60000,
        gop_cache: true,
        ping: 30,
        ping_timeout: 60
    },
    http: {
        port: 8000,
        mediaroot: './media',
        allow_origin: '*'
    },
    trans: {
        ffmpeg: './ffmpeg.exe',
        tasks: [
        {
            app: 'live',
            hls: true,
            hlsFlags: '[hls_time=2:hls_list_size=3:hls_flags=delete_segments]',
            dash: true,
            dashFlags: '[f=dash:window_size=3:extra_window_size=5]'
        }
        ]
    }
};
    

var nms = new NodeMediaServer(config);
nms.run();

var http = require('http');
var express = require('express');
const WebSocket = require('ws');

var app = express();
const wss = new WebSocket.Server({ noServer: true });

const os = require('os');
///获取本机ip///
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

setImmediate(()=>{
    var server = http.createServer(app);
    server.on('upgrade', function upgrade(request, socket, head) {
        wss.handleUpgrade(request, socket, head, function done(ws) {
            wss.emit('connection', ws, request);
        });
    });
    server.listen(80, ()=>{
        var address = getIPAdress();
        console.log(address);
        console.log('直播已经启动');
        console.log(`
FFMPEG推流：rtmp://${address}:1935/live/STREAM_NAME.flv
OBS推流（推荐）：
    服务器：rtmp://${address}:1935/live
    串流密钥：STREAM_NAME.flv
直播主页：http://${address}/
        `);
    });
});
 
wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(data) {
      wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
          client.send(data);
        }
      });
    });
});

const fs = require('fs');

app.get('/', (req, res)=>{
    res.write(fs.readFileSync('public/index.html'));
    res.end();
});